package com.alibaba.citrus.cr.sales.plan.facade.service.salesplan.adjust;

import com.alibaba.citrus.cr.common.annotation.FacadeInvoker;
import com.alibaba.citrus.cr.common.exception.FacadeException;
import com.alibaba.citrus.cr.common.util.DateUtils;
import com.alibaba.citrus.cr.sales.plan.api.salesplan.SalesPlanQueryService;
import com.alibaba.citrus.cr.sales.plan.model.SalesPlanReportAuditStatusEnum;
import com.alibaba.citrus.cr.sales.plan.model.SalesPlanReportStatusEnum;
import com.alibaba.citrus.cr.sales.plan.model.enums.SalesPlanModelEnum;
import com.alibaba.citrus.cr.sales.plan.model.enums.SalesPlanStatusEnum;
import com.alibaba.citrus.cr.sales.plan.model.enums.SalesStatBizTypeEnum;
import com.alibaba.citrus.cr.sales.plan.repository.SalesPlanRepository;
import com.alibaba.citrus.cr.sales.plan.sdo.SalesPlanReportSDO;
import com.alibaba.citrus.cr.sales.plan.sdo.SalesPlanSDO;
import com.alibaba.citrus.cr.sales.plan.api.salesplan.adjust.SalesPlanAdjustQueryService;
import com.alibaba.citrus.cr.sales.plan.api.salesplan.report.SalesPlanReportQueryService;
import com.alibaba.citrus.cr.sales.plan.dto.api.request.OrganizationSelectRequest;
import com.alibaba.citrus.cr.sales.plan.dto.api.request.PageQuerySalePlanAdjustRequest;
import com.alibaba.citrus.cr.sales.plan.dto.api.request.PageQuerySalePlanRequest;
import com.alibaba.citrus.cr.sales.plan.dto.api.request.QuerySalesPlanAdjustRequest;
import com.alibaba.citrus.cr.sales.plan.dto.api.request.QuerySalesPlanRequest;
import com.alibaba.citrus.cr.sales.plan.dto.api.request.SalesPlanReportQueryRequest;
import com.alibaba.cz.base.tool.StringUtil;
import com.alibaba.cz.base.tool.page.PageResult;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.epoch.app.bcorder.model.dto.OrganizationSDO;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author yuhailin
 * @description:
 * @date 2021-10-25 15:41
 */
@Service
public class SalesPlanAdjustQueryServiceImpl implements SalesPlanAdjustQueryService {
    @Resource
    SalesPlanRepository salesPlanRepository;

    @Resource
    SalesPlanReportQueryService salesPlanReportQueryService;

    @Resource
    SalesPlanQueryService salesPlanQueryService;

    @Override
    @FacadeInvoker
    public Result<PageResult<List<SalesPlanSDO>>> pageQuerySalesPlanAdjustList(PageQuerySalePlanAdjustRequest pageQuerySalePlanAdjustRequest) {
        PageQuerySalePlanRequest pageQuerySalePlanRequest = new PageQuerySalePlanRequest();
        BeanUtils.copyProperties(pageQuerySalePlanAdjustRequest, pageQuerySalePlanRequest);
        if (pageQuerySalePlanRequest.getBizType() != null) {
            if (StringUtil.isBlank(pageQuerySalePlanAdjustRequest.getOrgBusinessUnitCode())) {
                //查询登录人所属业务单元
                OrganizationSelectRequest organizationSelectRequest = new OrganizationSelectRequest();
                organizationSelectRequest.setRelatedOrganizationType(pageQuerySalePlanAdjustRequest.getRelatedOrganizationType());
                organizationSelectRequest.setRelatedOrganizationId(pageQuerySalePlanRequest.getRelatedOrganizationId());
                Result<List<OrganizationSDO>> listResult = salesPlanQueryService.organizationSelect(organizationSelectRequest);
                if (CollectionUtils.isNotEmpty(listResult.getResult())) {
                    List<String> orgBusinessUnitCodes = listResult.getResult().stream().map(OrganizationSDO::getId).distinct().filter(StringUtils::isNotEmpty).collect(Collectors.toList());
                    pageQuerySalePlanRequest.setOrgBusinessUnitCodes(orgBusinessUnitCodes);
                }
            }
            if (pageQuerySalePlanRequest.getBizType() < SalesStatBizTypeEnum.BUSINESS_UNIT.getOrganizationType()) {
                pageQuerySalePlanRequest.setBizType(null);
                pageQuerySalePlanRequest.setBizId(null);
            }
        }
        pageQuerySalePlanRequest.setDir("planTime");
        pageQuerySalePlanRequest.setAsc(false);
        PageResult<List<SalesPlanSDO>> listPageResult = salesPlanRepository.pageQuery(pageQuerySalePlanRequest);
        if (null != listPageResult && CollectionUtils.isNotEmpty(listPageResult.getContent())) {
            pageResultConverter(listPageResult, pageQuerySalePlanRequest);
        }
        return Result.success(listPageResult);
    }


    @Override
    @FacadeInvoker
    public Result<SalesPlanSDO> querySalesPlanAdjust(QuerySalesPlanAdjustRequest querySalesPlanAdjustRequest) {
        //分子公司以上的组织不用校验
        if (querySalesPlanAdjustRequest.getBizType() != null) {
            if (querySalesPlanAdjustRequest.getBizType() < SalesStatBizTypeEnum.BUSINESS_UNIT.getOrganizationType()) {
                querySalesPlanAdjustRequest.setBizType(null);
                querySalesPlanAdjustRequest.setBizId(null);
            }
        }
        QuerySalesPlanRequest querySalesPlanRequest = new QuerySalesPlanRequest();
        if (StringUtil.isNotEmpty(querySalesPlanAdjustRequest.getId())) {
            querySalesPlanRequest.setId(querySalesPlanAdjustRequest.getId());
        }
        SalesPlanSDO loadResult = salesPlanRepository.load(querySalesPlanRequest);
        if (Objects.nonNull(loadResult)) {
            loadResultConverter(loadResult, querySalesPlanAdjustRequest);
        }
        return Result.success(loadResult);
    }

    private void pageResultConverter(PageResult<List<SalesPlanSDO>> listPageResult, PageQuerySalePlanRequest pageQuerySalePlanRequest) {
        listPageResult.getContent().forEach(salesPlanSDO -> {
            if (StringUtil.isNotEmpty(salesPlanSDO.getPlanTime())) {
                //返回数据是时间戳,对时间戳做处理
                String planTime = DateUtils.stampToDate(salesPlanSDO.getPlanTime());
                try {
                    //2021年10月份
                    salesPlanSDO.setFormatPlanTime(DateUtils.formatPlanTime(planTime));
                    //2021-10-01 00:00:00
                    salesPlanSDO.setPlanTime(planTime);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            //审批状态
            if (pageQuerySalePlanRequest.getBizType() != null && StringUtil.isNotEmpty(pageQuerySalePlanRequest.getBizId())) {
                SalesStatBizTypeEnum byOrganizationType = SalesStatBizTypeEnum.getByOrganizationType(pageQuerySalePlanRequest.getBizType());
                if (byOrganizationType != null) {
//                    throw new FacadeException("OTS-02-002-02-15-007");
                    SalesPlanReportQueryRequest salesPlanReportQueryRequest = new SalesPlanReportQueryRequest();
                    salesPlanReportQueryRequest.setModelId(salesPlanSDO.getId().toString());
                    salesPlanReportQueryRequest.setModelType(salesPlanSDO.getModel());
                    salesPlanReportQueryRequest.setBizId(pageQuerySalePlanRequest.getBizId());
                    salesPlanReportQueryRequest.setBizType(byOrganizationType.getBizType());
                    Result<SalesPlanReportSDO> salesPlanReportSDOResult = salesPlanReportQueryService.querySalesPlanReport(salesPlanReportQueryRequest);
                    if (Objects.nonNull(salesPlanReportSDOResult.getResult())) {
                        salesPlanSDO.setAuditStatus(salesPlanReportSDOResult.getResult().getAuditStatus());
                        salesPlanSDO.setAuditStatusName(
                            SalesPlanReportAuditStatusEnum.of(salesPlanReportSDOResult.getResult().getAuditStatus()).getDesc());
                        salesPlanSDO.setReportStatus(salesPlanReportSDOResult.getResult().getStatus());
                        salesPlanSDO.setReportStatusName(
                            SalesPlanReportStatusEnum.of(salesPlanReportSDOResult.getResult().getStatus()).getDesc());
                    } else {
                        salesPlanSDO.setAuditStatus(SalesPlanReportAuditStatusEnum.TO_BE_REVIEW.getCode());
                        salesPlanSDO.setAuditStatusName(SalesPlanReportAuditStatusEnum.TO_BE_REVIEW.getDesc());
                        salesPlanSDO.setReportStatus(SalesPlanReportStatusEnum.TO_REPORT.getCode());
                        salesPlanSDO.setReportStatusName(SalesPlanReportStatusEnum.TO_REPORT.getDesc());
                    }
                } else {
                    salesPlanSDO.setAuditStatus(SalesPlanReportAuditStatusEnum.TO_BE_REVIEW.getCode());
                    salesPlanSDO.setAuditStatusName(SalesPlanReportAuditStatusEnum.TO_BE_REVIEW.getDesc());
                    salesPlanSDO.setReportStatus(SalesPlanReportStatusEnum.TO_REPORT.getCode());
                    salesPlanSDO.setReportStatusName(SalesPlanReportStatusEnum.TO_REPORT.getDesc());
                }
            }
            //状态
            salesPlanSDO.setStatusDesc(SalesPlanStatusEnum.getDesc(salesPlanSDO.getStatus()));

            //发布按钮
            boolean isPublish = true;
            //处理按钮
            boolean isAudit = true;
            //20240516 一盘货上线后,调整由大区处理
//            if (SalesPlanModelEnum.PLAN_MODEL.getModel().equals(salesPlanSDO.getModel())) {
//                if (salesPlanSDO.getStatus() >= SalesPlanStatusEnum.TO_BE_PUBLISHED.getCode()) {
//                    isPublish = false;
//                }
//            } else {
//                if (salesPlanSDO.getStatus() >= SalesPlanStatusEnum.ADJUSTED_TO_BE_PUBLISHED.getCode() || salesPlanSDO.getStatus().equals(SalesPlanStatusEnum.PUBLISHED.getCode())) {
//                    isPublish = false;
//                }
//                if (!SalesPlanStatusEnum.PUBLISHED.getCode().equals(salesPlanSDO.getStatus())
////                        && SalesPlanReportAuditStatusEnum.TO_BE_REVIEW.getCode() .equals(salesPlanSDO.getAuditStatus())
//                ) {
//                    isAudit = false;
//                }
//            }
            salesPlanSDO.setIsAudit(isAudit);
            salesPlanSDO.setIsPublish(isPublish);
            salesPlanSDO.setStatusInfo(getStatusDesc(salesPlanSDO.getStatus() == null ? null : salesPlanSDO.getStatus()));
        });
    }

    public static com.alibaba.fastjson.JSONObject getStatusDesc(Integer type) {
        if (type == null)
            return null;
        if (type == SalesPlanStatusEnum.TO_BE_LOCKED.getCode()) {
            return generateStatus(SalesPlanStatusEnum.TO_BE_LOCKED.getDesc(), "success");
        } else if (type == SalesPlanStatusEnum.TO_BE_SYNC.getCode()) {
            return generateStatus(SalesPlanStatusEnum.TO_BE_SYNC.getDesc(), "warning");
        } else if (type == SalesPlanStatusEnum.TO_BE_REPLIED.getCode()) {
            return generateStatus(SalesPlanStatusEnum.TO_BE_REPLIED.getDesc(), "error");
        } else if (type == SalesPlanStatusEnum.TO_BE_PUBLISHED.getCode()) {
            return generateStatus(SalesPlanStatusEnum.TO_BE_PUBLISHED.getDesc(), "warning");
        } else if (type == SalesPlanStatusEnum.PUBLISHED.getCode()) {
            return generateStatus(SalesPlanStatusEnum.PUBLISHED.getDesc(), "middle");
        } else if (type == SalesPlanStatusEnum.ADJUST.getCode()) {
            return generateStatus(SalesPlanStatusEnum.ADJUST.getDesc(), "middle");
        } else if (type == SalesPlanStatusEnum.ADJUSTED_TO_BE_REPLIED.getCode()) {
            return generateStatus(SalesPlanStatusEnum.ADJUSTED_TO_BE_REPLIED.getDesc(), "success");
        } else if (type == SalesPlanStatusEnum.ADJUSTED_TO_BE_PUBLISHED.getCode()) {
            return generateStatus(SalesPlanStatusEnum.ADJUSTED_TO_BE_PUBLISHED.getDesc(), "middle");
        } else if (type == SalesPlanStatusEnum.CANCEL.getCode()) {
            return generateStatus(SalesPlanStatusEnum.CANCEL.getDesc(), "cancel");
        }
        return null;
    }

    public static com.alibaba.fastjson.JSONObject generateStatus(String msg, String color) {
        com.alibaba.fastjson.JSONObject obj = new com.alibaba.fastjson.JSONObject();
        obj.put("text", msg);
        obj.put("type", color);
        return obj;
    }

    private void loadResultConverter(SalesPlanSDO loadResult, QuerySalesPlanAdjustRequest querySalesPlanAdjustRequest) {
        //状态
        loadResult.setStatusDesc(SalesPlanStatusEnum.getDesc(loadResult.getStatus()));
        if (StringUtil.isNotEmpty(loadResult.getPlanTime())) {
            //返回数据是时间戳,对时间戳做处理
            String planTime = DateUtils.stampToDate(loadResult.getPlanTime());
            try {
                //2021年10月份
                loadResult.setFormatPlanTime(DateUtils.formatPlanTime(planTime));
                //2021-10-01 00:00:00
                loadResult.setPlanTime(planTime);
            } catch (Exception e) {
                e.printStackTrace();
            }

            //审批状态
            if (querySalesPlanAdjustRequest.getBizType() != null && StringUtil.isNotEmpty(querySalesPlanAdjustRequest.getBizId())) {
                SalesStatBizTypeEnum byOrganizationType = SalesStatBizTypeEnum.getByOrganizationType(querySalesPlanAdjustRequest.getBizType());
                if (byOrganizationType == null) {
                    throw new FacadeException("OTS-02-002-02-15-007");
                }
                SalesPlanReportQueryRequest salesPlanReportQueryRequest = new SalesPlanReportQueryRequest();
                salesPlanReportQueryRequest.setModelId(loadResult.getId().toString());
                salesPlanReportQueryRequest.setModelType(loadResult.getModel());
                salesPlanReportQueryRequest.setBizId(querySalesPlanAdjustRequest.getBizId());
                salesPlanReportQueryRequest.setBizType(byOrganizationType.getBizType());
                Result<SalesPlanReportSDO> salesPlanReportSDOResult = salesPlanReportQueryService.querySalesPlanReport(salesPlanReportQueryRequest);
                if (Objects.nonNull(salesPlanReportSDOResult.getResult())) {
                    loadResult.setAuditStatus(salesPlanReportSDOResult.getResult().getAuditStatus());
                    loadResult.setAuditStatusName(SalesPlanReportAuditStatusEnum.of(salesPlanReportSDOResult.getResult().getAuditStatus()).getDesc());
                    loadResult.setReportStatus(salesPlanReportSDOResult.getResult().getStatus());
                    loadResult.setReportStatusName(SalesPlanReportStatusEnum.of(salesPlanReportSDOResult.getResult().getStatus()).getDesc());
                } else {
                    loadResult.setAuditStatus(SalesPlanReportAuditStatusEnum.TO_BE_REVIEW.getCode());
                    loadResult.setAuditStatusName(SalesPlanReportAuditStatusEnum.TO_BE_REVIEW.getDesc());
                    loadResult.setReportStatus(SalesPlanReportStatusEnum.TO_REPORT.getCode());
                    loadResult.setReportStatusName(SalesPlanReportStatusEnum.TO_REPORT.getDesc());
                }
            }
        }

    }

}
